#!/bin/bash

UPDATE_FOLDER="/home/cat/Downloads/bj2"
TARGET_DIR="/usr/local/bin"
PROGRAM_DIR="$TARGET_DIR/bj2"
PROGRAM_NAME="bj-timer"


# 检查文件夹是否为空
if [[ -n "$(ls -A "$UPDATE_FOLDER" 2>/dev/null)" ]]; then
    echo "Moving update files to $TARGET_DIR..."
    
    # 停止当前正在运行的程序（如果存在）
    if pkill -f "$PROGRAM_NAME"; then
        echo "Stopped running $PROGRAM_NAME instance."
    fi
    
    # 使用rsync同步文件（保留权限）
    if rsync -rlt --delete --info=progress2 "$UPDATE_FOLDER/" "$PROGRAM_DIR/"; then
        echo "Update files synced successfully."
    else
        echo "Error: rsync failed with exit code $?!" >&2
    fi

    # 重启系统以应用更新
    # sleep 3
    # echo a1025863915 | sudo -S reboot

else
    echo "$UPDATE_FOLDER is empty. No files to update."
fi

# 清理下载目录（只移除bj2文件夹）
if rm -rf "$UPDATE_FOLDER"; then
    echo "Download directory cleaned."
else
    echo "Warning: Failed to clean download directory." >&2
fi


# 键盘插入检测
/usr/bin/python3 /usr/local/bin/bj2/display_check_daemon.py &

# 等待seaudio 音频服务
while ! pgrep pulseaudio > /dev/null; do sleep 1; done
sleep 2
pactl set-default-sink alsa_output.platform-es8388-sound.HiFi__hw_rockchipes8388__sink

# 设置环境变量
# export LD_LIBRARY_PATH=/usr/local/bin/bj2/lib

sleep 2


# 启动程序部分 - 添加在这里
echo "Starting $PROGRAM_NAME..."
cd "$PROGRAM_DIR" || { echo "Error: Failed to enter $PROGRAM_DIR!" >&2; }

# 确认程序存在
if [[ ! -f "./$PROGRAM_NAME" ]]; then
    echo "Error: $PROGRAM_NAME not found in $PROGRAM_DIR!" >&2
    exit 1
fi

# 确保程序可执行
if ! chmod +x "./$PROGRAM_NAME"; then
    echo "Warning: Failed to set executable permission!" >&2
fi


LOG_FILE="${PROGRAM_NAME}.log"
./$PROGRAM_NAME >"$LOG_FILE" 2>&1 &


gsettings set org.gnome.shell.extensions.dash-to-dock show-show-apps-button false
